package yongxin.controller.processreport;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.poi.excel.export.template.ExcelExportOfTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.BrowserUtils;
import org.jeecgframework.core.util.StringUtil;

import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import yongxin.entity.matchinegroup.MatchinegroupEntity;
import yongxin.entity.process.ProcessEntity;
import yongxin.entity.processreport.MakingReportEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.rolling.RollingEntity;
import yongxin.entity.tasks.TasksEntity;
import yongxin.entity.workshop.WorkshopEntity;
import yongxin.service.matchinegroup.MatchinegroupServiceI;
import yongxin.service.process.ProcessServiceI;
import yongxin.service.processreport.ProcessReportServiceI;
import yongxin.service.rolling.RollingServiceI;
import yongxin.service.tasks.TasksServiceI;
import yongxin.service.workshop.WorkshopServiceI;
import yongxin.utils.ExcelUtils;
import yongxin.vo.ReportDetail;

/**
 * @Title: Controller
 * @Description: 工序汇报
 * @author zhangdaihao
 * @date 2015-02-05 14:03:13
 * @version V1.0
 * 
 */
@Controller
@RequestMapping("/processReportController")
public class ProcessReportController extends BaseController
{
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ProcessReportController.class);

	@Autowired
	private ProcessReportServiceI processReportService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ProcessServiceI processService;
	@Autowired
	private RollingServiceI rollingService;
	@Autowired
	private TasksServiceI tasksService;
	@Autowired
	private WorkshopServiceI workshopService;

	private String message;

	public String getMessage()
	{
		return message;
	}

	public void setMessage(String message)
	{
		this.message = message;
	}

	/**
	 * 工序汇报列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "processReport")
	public ModelAndView processReport(HttpServletRequest request)
	{
		String process = request.getParameter("process");
		request.setAttribute("process", process);
		if (process.equals("p4"))
		{
			return new ModelAndView("yongxin/process/processReportList_p4");
			
		} else if (process.equals("over"))
		{
			return new ModelAndView("yongxin/process/processReportList_over");
		} else
		{
			return new ModelAndView("yongxin/process/processReportList");
		}
	}

	/**
	 * 已完工报表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "completedReport")
	public ModelAndView completedReport(HttpServletRequest request)
	{   
		String type=request.getParameter("type");
		request.setAttribute("type", type);
		return new ModelAndView("yongxin/reports/processReportList_completed");
	}

	/**
	 * 在制品报表页面跳转
	 * 
	 */
	@RequestMapping(params = "makingReport")
	public ModelAndView makingReport(HttpServletRequest request)
	{
		String type=request.getParameter("type");
		request.setAttribute("type", type);
		return new ModelAndView("yongxin/reports/processReportList_making");

	}
    
	/**
	 * 汇总
	 * 
	 */
	@RequestMapping(params = "totalReport")
	public ModelAndView totalReport(HttpServletRequest request)
	{
		String type = request.getParameter("type");
		request.setAttribute("type", type);
		return new ModelAndView("yongxin/reports/processReportList_total");

	}
	
	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ProcessReportEntity processReport, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid)
	{
        
		String process = request.getParameter("process");
		
		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		// 查询条件组装器
		cq.eq("cprocess", process);
		if (StringUtil.isEmpty(processReport.getFstate()))
		{
			cq.in("fstate", new Object[] { "0", "1" });
		}
		
		String sql = "select AVG(CONVERT(numeric(19,2), (SUBSTRING(frate,1,CHARINDEX('%',frate,1)-1)))) avg_frate from t_processreport where fstate = '2' and cprocess = ?";

		// 根据用户(不锈钢组或碳钢)来显示
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
		if (user.getUserName().contains("bxg"))
		{
			cq.like("fbcph", "S%");
			sql += " and fbcph like 'S%' ";

		} else if (user.getUserName().contains("tg"))
		{
			cq.like("fbcph", "Y%");
			sql += " and fbcph like 'Y%' ";
		}
        
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
		
		
		this.systemService.getDataGridReturn(cq, true);
		
		
		// 计算平均成材率
		if (StringUtil.isNotEmpty(processReport.getFstate()) && processReport.getFstate().equals("2"))
		{
		//	List<ProcessReportEntity> processReports = this.processReportService.getListByCriteriaQuery(cq, true);
			List<ProcessReportEntity> processReports = dataGrid.getResults();
			BigDecimal sum_trzl = new BigDecimal("0.00");  
			BigDecimal sum_cczl = new BigDecimal("0.00"); 
			for (ProcessReportEntity processReportEntity : processReports)
			{
				BigDecimal trzl = new BigDecimal(processReportEntity.getFtrzl()); 
				sum_trzl =  sum_trzl.add(trzl);
				BigDecimal cczl = new BigDecimal(processReportEntity.getFcczl()); 
				sum_cczl =  sum_cczl.add(cczl);
			}
            
			if(sum_trzl.compareTo(new BigDecimal("0.00")) == 1)
			{
				
				BigDecimal rate = sum_cczl.divide(sum_trzl,5,BigDecimal.ROUND_CEILING);
			    NumberFormat percent = NumberFormat.getPercentInstance();  //建立百分比格式化引用 
			    percent.setMaximumFractionDigits(2); //百分比小数点最多3位 
				
				dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl,frate:" + percent.format(rate));
				
			}
		

		} else
		{

			dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl");
		}
		System.err.println(dataGrid.getFooter());
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 已完成报表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "completed_dataGrid")
	public void completed_dataGrid(ProcessReportEntity processReport, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid)
	{

		String cprocess = request.getParameter("cprocess");
		String type = request.getParameter("type");               // 产品类型
		
		String fbcph = request.getParameter("fbcph");
		String fworkgroup = request.getParameter("fworkgroup");
		String updateDate_begin = request.getParameter("updateDate_begin");
		String updateDate_end = request.getParameter("updateDate_end");
		
		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		// 查询条件组装器
		String sql = " select cast(Convert(decimal(28,2),round(SUM(Convert(decimal(18,2),isnull(fcczl,0)))/SUM(Convert(decimal(18,2),isnull(ftrzl,0)))*100,2)) as varchar(10)) + '%' avg_frate from t_processreport where fstate = '2'  ";
		
		if (StringUtil.isNotEmpty(type))
		{
			if (type.equals("S"))
			{
				cq.like("fbcph", "S%");
				sql += " and fbcph like 'S%' ";
			} else if (type.equals("Y"))
			{
				cq.like("fbcph", "Y%");
				sql += " and fbcph like 'Y%' ";
			}
			if (StringUtil.isNotEmpty(cprocess))
			{
				sql += " and  cprocess = '" + cprocess + "'";
			}

		}
		
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " and fworkgroup = '" + fworkgroup + "'";
		}
		if(StringUtil.isNotEmpty(fbcph)){
			sql += " and fbcph like '%" + fbcph + "%'";
		}
		if(StringUtil.isNotEmpty(updateDate_begin)){
			sql += " and update_date >= '" + updateDate_begin + "'";
		}
		if(StringUtil.isNotEmpty(updateDate_end)){
			sql += " and update_date <= '" + updateDate_end + "'";
		}
		
		cq.eq("fstate", "2");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());

		this.systemService.getDataGridReturn(cq, true);
		String avg_frate =  String.valueOf(processService.findOneForJdbc(sql).get("avg_frate"));

		dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl,frate:" + avg_frate);
		TagUtil.datagrid(response, dataGrid);
		
	}

	// 在制品报表
	@RequestMapping(params = "making_datagrid")
	public void making_datagrid(ProcessReportEntity processReport, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid)
	{

		String type = request.getParameter("type");   // 产品类型
		
		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		// 查询条件组装器
		String sql = "select sum(CONVERT(numeric(19,2),ftrzl)) sum_trzl from t_processreport where fstate in(0,1,4)  ";
		
		if (StringUtil.isNotEmpty(type))
		{
			if (type.equals("S"))
			{
				cq.like("fbcph", "S%");
				sql += " and fbcph like 'S%' ";

			} else if (type.equals("Y"))
			{
				cq.like("fbcph", "Y%");
				sql += " and fbcph like 'Y%' ";
			}

		}
		
		cq.in("fstate", new Object[] { "0", "1", "4" });
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
		this.systemService.getDataGridReturn(cq, true);
		String total_trzl = String.valueOf(processReportService.findOneForJdbc(sql).get("sum_trzl"));
		total_trzl = total_trzl == "null" ? "" : total_trzl;

		dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl");
		TagUtil.datagrid(response, dataGrid);
	}

	
	
	/**
	 * 汇总报表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "total_dataGrid")
	public void total_dataGrid(ProcessReportEntity processReport, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid)
	{

		String type = request.getParameter("type");   // 产品类型
		
		String year = request.getParameter("year");
		String cprocess = request.getParameter("cprocess");
		String fworkgroup = request.getParameter("fworkgroup");
		
		String sql = " select cprocess,CONVERT(varchar(50),YEAR(update_date)) + '-' + CONVERT(varchar(50),Month(update_date)) as mo,YEAR(update_date) year,Month(update_date) month,          ";
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " fworkgroup, ";
		}
		sql += " SUM(Convert(decimal(18,2),isnull(ftrzl,0))) sum_trzl,SUM(Convert(decimal(18,2),isnull(fcczl,0))) sum_cczl,SUM(Convert(decimal(18,2),dbo.isNullOrEmpty(fbfzl,0))) sum_bfzl,  ";
		sql += " cast(Convert(decimal(28,2),round(SUM(Convert(decimal(18,2),isnull(fcczl,0)))/SUM(Convert(decimal(18,2),isnull(ftrzl,0)))*100,2)) as varchar(10)) + '%' avg_frate            ";
		sql += "   from t_processreport where fstate = '2'                                                                                                                                   ";
		
		if (StringUtil.isNotEmpty(type))
		{
			if (type.equals("S"))
			{
				sql += " and fbcph like 'S%' ";

			} else if (type.equals("Y"))
			{
				sql += " and fbcph like 'Y%' ";
			}

		}
		
		
		if(StringUtil.isNotEmpty(cprocess)){
			sql += " and cprocess = '" + cprocess + "' ";
		}
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " and fworkgroup = '" + fworkgroup + "' ";
		}
		if(StringUtil.isNotEmpty(year)){
			sql += " and YEAR(update_date) = " + year ;
		}
		sql += " group by YEAR(update_date),Month(update_date),cprocess";
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " , fworkgroup ";
		}
		sql += " order by year,month";
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " , fworkgroup ";
		}
		List<Map<String, Object>> maplist = null;
		List<Map<String, Object>> allmaplist = null;

		try
		{
			allmaplist = systemService.findForJdbc(sql);
			maplist = systemService.findForJdbcParam(sql, dataGrid.getPage(), dataGrid.getRows());

		} catch (Exception ex)
		{

		}
		dataGrid.setTotal(allmaplist.size());
		dataGrid.setResults(maplist);
		// 数量和金额合计
		BigDecimal qty1 = new BigDecimal("0.00");
		BigDecimal qty2 = new BigDecimal("0.00");
		BigDecimal qty3 = new BigDecimal("0.00");
		for (Map<String, Object> map : maplist)
		{
			qty1 = qty1.add((BigDecimal) map.get("sum_trzl"));
			qty2 = qty2.add((BigDecimal) map.get("sum_bfzl"));
			qty3 = qty3.add((BigDecimal) map.get("sum_cczl"));
		}
		
		dataGrid.setFooter("cprocess:合计,sum_trzl:" + qty1 + ",sum_bfzl:" + qty2 + ",sum_cczl:" + qty3);
		TagUtil.datagrid(response, dataGrid);
		
	}
	
	/**
	 * 
	 * 導出
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "exportXlsByT_total")
	public void exportXlsByT_total(HttpServletRequest request,HttpServletResponse response, DataGrid dataGrid) {
		
	
		String year = request.getParameter("year");
		String cprocess = request.getParameter("cprocess");
		String fworkgroup = request.getParameter("fworkgroup");
     
		String type = request.getParameter("type");   // 产品类型
		
		String sql = " select cprocess,CONVERT(varchar(50),YEAR(update_date)) + '-' + CONVERT(varchar(50),Month(update_date)) as mo,YEAR(update_date) year,Month(update_date) month,           ";
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " fworkgroup, ";
		}
		sql += " SUM(Convert(decimal(18,2),isnull(ftrzl,0))) sum_trzl,SUM(Convert(decimal(18,2),isnull(fcczl,0))) sum_cczl,SUM(Convert(decimal(18,2),dbo.isNullOrEmpty(fbfzl,0))) sum_bfzl,  ";
		sql += " cast(Convert(decimal(28,2),round(SUM(Convert(decimal(18,2),isnull(fcczl,0)))/SUM(Convert(decimal(18,2),isnull(ftrzl,0)))*100,2)) as varchar(10)) + '%' avg_frate            ";
		sql += "   from t_processreport where fstate = '2'                                                                                                                                   ";
		if (StringUtil.isNotEmpty(type))
		{
			if (type.equals("S"))
			{
				sql += " and fbcph like 'S%' ";

			} else if (type.equals("Y"))
			{
				sql += " and fbcph like 'Y%' ";
			}

		}
		if(StringUtil.isNotEmpty(cprocess)){
			sql += " and cprocess = '" + cprocess + "' ";
		}
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " and fworkgroup = '" + fworkgroup + "' ";
		}
		if(StringUtil.isNotEmpty(year)){
			sql += " and YEAR(update_date) = " + year ;
		}
		sql += " group by YEAR(update_date),Month(update_date),cprocess";
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " , fworkgroup ";
		}
		sql += " order by year,month";
		if(StringUtil.isNotEmpty(fworkgroup)){
			sql += " , fworkgroup ";
		}
          

		
		List<Map<String, Object>> maplist = null;

		try
		{
			maplist = systemService.findForJdbc(sql);
			List<String[]> list = new ArrayList<String[]>();
			
			for (Map<String, Object> map : maplist) {
				String[] arr = new String[map.size()];
				arr[0] = (String) map.get("cprocess");
				arr[1] = (String) map.get("mo");
				arr[2] =  String.valueOf((BigDecimal) map.get("sum_trzl"));
				arr[3] =  String.valueOf((BigDecimal) map.get("sum_bfzl"));
				arr[4] =   String.valueOf((BigDecimal) map.get("sum_cczl"));
				arr[5] = (String) map.get("avg_frate");
				list.add(arr);
				 
			}
		
	
			String[] columnNames = new String[] { "工序", "月份", "投入重量", "报废重量","产出重量","平均成材率"};
	       String titleName = "生产汇总表.xls";

			OutputStream fOut = response.getOutputStream();
			response.setHeader("Content-Disposition", "attachment; filename="
					+ new String(titleName.getBytes("GB2312"), "ISO8859-1"));

	        ExcelUtils.create(request, list, columnNames, titleName, fOut);
			
		} catch (Exception ex)
		{

		}
		
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	// 碳钢在制品报表
	@RequestMapping(params = "cg_making_datagrid")
	public void cg_making_datagrid(ProcessReportEntity processReport, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid)
	{

		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		// 查询条件组装器
		cq.in("fstate", new Object[] { "0", "1", "4" });
		cq.like("fbcph", "Y");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
		this.systemService.getDataGridReturn(cq, true);

		dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl");
		TagUtil.datagrid(response, dataGrid);
	}

	// 不锈钢在制品报表
	@RequestMapping(params = "bxg_making_datagrid")
	public void bxg_making_datagrid(ProcessReportEntity processReport, HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid)
	{

		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		// 查询条件组装器
		cq.in("fstate", new Object[] { "0", "1", "4" });
		cq.like("fbcph", "S");
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
		this.systemService.getDataGridReturn(cq, true);
		dataGrid.setFooter("ftrkd:合计,ftrzl,fcczl,fbfzl");
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除工序汇报
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(ProcessReportEntity processReport, HttpServletRequest request)
	{
		AjaxJson j = new AjaxJson();
		processReport = systemService.getEntity(ProcessReportEntity.class, processReport.getId());
		message = "工序汇报删除成功";
		processReportService.delete(processReport);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);

		j.setMsg(message);
		return j;
	}

	/**
	 * 添加工序汇报
	 * 
	 * @param processReport
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(ProcessReportEntity processReport, HttpServletRequest request)
	{

		AjaxJson j = new AjaxJson();
		String nprocess = request.getParameter("nprocess");
		String process = request.getParameter("process");
		String fwlname = request.getParameter("fwlname"); // 物料名称


		List<ReportDetail> details=new ArrayList<>();   //完工汇报记录

		if (processReport.getFbcph().split(",").length > 1) // 分卷
		{
			String[] fbcph = processReport.getFbcph().split(",");

			String[] ftrkds = request.getParameterValues("ftrkd");
			String[] ftrhds = request.getParameterValues("ftrhd");
			String[] ftrzls = request.getParameterValues("ftrzl");
			String[] fcckds = request.getParameterValues("fcckd");
			String[] fcchds = request.getParameterValues("fcchd");
			String[] fcczls = request.getParameterValues("fcczl");
			String[] fbfzls = request.getParameterValues("fbfzl");
			String[] frates = request.getParameterValues("frate");
			String[] fnotes = request.getParameterValues("fnote");
			String[] fnprocesss = request.getParameterValues("nprocess");

			try
			{

				message = "工序汇报成功";
				ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
				t.setFstate("3"); // 标记为分卷
				t.setCreateBy(processReport.getCreateBy());
				t.setCreateDate(processReport.getCreateDate());
				processReportService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e)
			{
				e.printStackTrace();
				message = "工序汇报失败";
			}

			// 保存汇报记录
			for (int i = 0; i < fbcph.length; i++)
			{

				try
				{
					ProcessReportEntity t = new ProcessReportEntity();
					MyBeanUtils.copyBeanNotNull2Bean(processReport, t);

					t.setFwlname(fwlname);
					t.setFbcph(fbcph[i]);
					t.setFtrhd(ftrhds[i]);
					t.setFtrkd(ftrkds[i]);
					t.setFtrzl(ftrzls[i]);
					t.setFcchd(fcchds[i]);
					t.setFcckd(fcckds[i]);
					t.setFcczl(fcczls[i]);
					t.setFbfzl(fbfzls[i]);
					t.setFrate(frates[i]);
					t.setFnote(fnotes[i]);
					Date date = new Date();
					t.setUpdateDate(date);
					t.setNprocess(fnprocesss[i]);

					// 如果是轧机汇报 保存轧机工艺
					if (process != null && (process.equals("p2_1") || process.equals("p2_2")))
					{
						String[] ids = request.getParameterValues("r_id");
						String[] fkjhd = request.getParameterValues("fkjhd");
						String[] fsjhd = request.getParameterValues("fsjhd");
						String[] fkjzl = request.getParameterValues("fkjzl");
						String[] fsjzl = request.getParameterValues("fsjzl");
						String[] fzzl = request.getParameterValues("fzzl");
						String[] fsd = request.getParameterValues("fsd");
						String[] fyxl = request.getParameterValues("fyxl");
						String[] fzhxxs = request.getParameterValues("fzhxx");
						String[] fhms = request.getParameterValues("fhm");
						String[] note = request.getParameterValues("note");

						// 对于轧机工艺，先删除，再保存
						String hql = "delete from t_rolling where fhbid = ?";
						int row = rollingService.executeSql(hql, t.getId());

						for (int j1 = 0; j1 < fkjhd.length; j1++)
						{

							RollingEntity rolling = new RollingEntity();
							rolling.setFhbid(t.getId());
							rolling.setFdc(String.valueOf(1 + j1));
							rolling.setFkjhd(fkjhd[j1]);
							rolling.setFsjhd(fsjhd[j1]);
							rolling.setFkjzl(fkjzl[j1]);
							rolling.setFsjzl(fsjzl[j1]);
							rolling.setFzzl(fzzl[j1]);
							rolling.setFsd(fsd[j1]);
							rolling.setFyxl(fyxl[j1]);
							rolling.setFzhxx(fzhxxs[j1]);
							rolling.setFhm(fhms[j1]);
							rolling.setFnote(note[j1]);
							rollingService.saveOrUpdate(rolling);
						}
					}

					if (processReport.getFstate().equals("2"))
					{

						if (!fnprocesss[i].equals("over"))
						{
							// 保存一下工序待汇报记录
							ProcessReportEntity nprocessReport = new ProcessReportEntity();
							nprocessReport.setFwlname(fwlname);
							nprocessReport.setCprocess(fnprocesss[i]);
							nprocessReport.setFbcph(fbcph[i]);
							nprocessReport.setFtrhd(fcchds[i]);
							nprocessReport.setFtrkd(fcckds[i]);
							nprocessReport.setFtrzl(fcczls[i]);
							nprocessReport.setFstate("0");
							processReportService.save(nprocessReport);

							ProcessEntity entity = new ProcessEntity();
							entity.setFreportid(nprocessReport.getId());
							entity.setFbcph(fbcph[i]);
							entity.setFprocess(fnprocesss[i]);
							processService.save(entity);

							t.setfNextReportId(nprocessReport.getId()); // 跟下一道工序关联
						} else
						{
							ProcessEntity entity = new ProcessEntity();
							entity.setFbcph(fbcph[i]);
							entity.setFprocess(fnprocesss[i]);
							processService.save(entity);


							ReportDetail detail=new ReportDetail();
							detail.setFbcph(t.getFbcph());
							detail.setFcchd(t.getFcchd());
							detail.setFcckd(t.getFcckd());
							detail.setFcczl(t.getFcczl());
							detail.setFwlname(t.getFwlname());
							details.add(detail);

						}
					}
					processReportService.save(t);

					processReportService.uploadTaskReportToOver(t.getId(),details);

				} catch (Exception e)
				{
					e.printStackTrace();
					message = "工序汇报失败";
				}

			}
		} else if (StringUtil.isNotEmpty(processReport.getId()))
		{
			message = "工序汇报成功";
			ProcessReportEntity t = processReportService.get(ProcessReportEntity.class, processReport.getId());
			try
			{
				MyBeanUtils.copyBeanNotNull2Bean(processReport, t);

				// 汇报
				if (processReport.getFstate().equals("2"))
				{

					if (!processReport.getNprocess().equals("over"))
					{
						ProcessReportEntity nprocessReport = new ProcessReportEntity();
						nprocessReport.setCprocess(processReport.getNprocess());
						nprocessReport.setFwlname(fwlname);
						nprocessReport.setFbcph(processReport.getFbcph());
						nprocessReport.setFtrhd(processReport.getFcchd());
						nprocessReport.setFtrkd(processReport.getFcckd());
						nprocessReport.setFtrzl(processReport.getFcczl());
						nprocessReport.setFwlname(processReport.getFwlname());
						nprocessReport.setFstate("0");
						processReportService.save(nprocessReport);

						ProcessEntity entity = new ProcessEntity();
						entity.setFreportid(nprocessReport.getId());
						entity.setFbcph(processReport.getFbcph());
						entity.setFprocess(processReport.getNprocess());
						processService.save(entity);

						t.setfNextReportId(nprocessReport.getId()); // 跟下道工序关联

					} else
					{
						ProcessEntity entity = new ProcessEntity();
						entity.setFbcph(processReport.getFbcph());
						entity.setFprocess(processReport.getNprocess());
						processService.save(entity);

						ReportDetail detail=new ReportDetail();
						detail.setFbcph(t.getFbcph());
						detail.setFcchd(t.getFcchd());
						detail.setFcckd(t.getFcckd());
						detail.setFcczl(t.getFcczl());
						detail.setFwlname(t.getFwlname());
						details.add(detail);

					}
					// 汇报 -保存轧制工序
					if (process != null && (process.equals("p2_1") || process.equals("p2_2")))
					{
						String[] ids = request.getParameterValues("r_id");
						String[] fkjhd = request.getParameterValues("fkjhd");
						String[] fsjhd = request.getParameterValues("fsjhd");
						String[] fkjzl = request.getParameterValues("fkjzl");
						String[] fsjzl = request.getParameterValues("fsjzl");
						String[] fzzl = request.getParameterValues("fzzl");
						String[] fsd = request.getParameterValues("fsd");
						String[] fyxl = request.getParameterValues("fyxl");
						String[] fzhxxs = request.getParameterValues("fzhxx");
						String[] fhms = request.getParameterValues("fhm");
						String[] note = request.getParameterValues("note");

						// 对于轧机工艺，先删除，再保存
						String hql = "delete from t_rolling where fhbid = ?";
						int row = rollingService.executeSql(hql, t.getId());

						for (int i = 0; i < fkjhd.length; i++)
						{

							RollingEntity rolling = new RollingEntity();
							rolling.setFhbid(processReport.getId());
							rolling.setFdc(String.valueOf(1 + i));
							rolling.setFkjhd(fkjhd[i]);
							rolling.setFsjhd(fsjhd[i]);
							rolling.setFkjzl(fkjzl[i]);
							rolling.setFsjzl(fsjzl[i]);
							rolling.setFzzl(fzzl[i]);
							rolling.setFsd(fsd[i]);
							rolling.setFyxl(fyxl[i]);
							rolling.setFzhxx(fzhxxs[i]);
							rolling.setFhm(fhms[i]);
							rolling.setFnote(note[i]);
							rollingService.saveOrUpdate(rolling);
						}
					}

				} else if (processReport.getFstate().equals("1"))
				{

					// 保存轧机工艺
					if (process != null && (process.equals("p2_1") || process.equals("p2_2")))
					{
						String[] ids = request.getParameterValues("r_id");
						String[] fkjhd = request.getParameterValues("fkjhd");
						String[] fsjhd = request.getParameterValues("fsjhd");
						String[] fkjzl = request.getParameterValues("fkjzl");
						String[] fsjzl = request.getParameterValues("fsjzl");
						String[] fzzl = request.getParameterValues("fzzl");
						String[] fsd = request.getParameterValues("fsd");
						String[] fyxl = request.getParameterValues("fyxl");
						String[] fzhxxs = request.getParameterValues("fzhxx");
						String[] fhms = request.getParameterValues("fhm");
						String[] note = request.getParameterValues("note");

						// 对于轧机工艺，先删除，再保存
						String hql = "delete from t_rolling where fhbid = ?";
						int row = rollingService.executeSql(hql, t.getId());

						for (int i = 0; i < fkjhd.length; i++)
						{
							RollingEntity rolling = new RollingEntity();
							rolling.setFhbid(processReport.getId());
							rolling.setFdc(String.valueOf(1 + i));
							rolling.setFkjhd(fkjhd[i]);
							rolling.setFsjhd(fsjhd[i]);
							rolling.setFkjzl(fkjzl[i]);
							rolling.setFsjzl(fsjzl[i]);
							rolling.setFzzl(fzzl[i]);
							rolling.setFsd(fsd[i]);
							rolling.setFyxl(fyxl[i]);
							rolling.setFzhxx(fzhxxs[i]);
							rolling.setFhm(fhms[i]);
							rolling.setFnote(note[i]);
							rollingService.saveOrUpdate(rolling);

						}
					}
				}

				processReportService.saveOrUpdate(t);

				processReportService.uploadTaskReportToOver(t.getId(),details);
				
				
				
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);

			} catch (Exception e)
			{
				e.printStackTrace();
				message = "工序汇报失败";
			}
		}

		j.setMsg(message);
		return j;
	}

	@RequestMapping(params = "returnReport")
	@ResponseBody
	public AjaxJson returnReport(ProcessReportEntity processReport, HttpServletRequest request)
	{

		AjaxJson j = new AjaxJson();

		// 获取汇报id、下一工序id、本场批号
		String id = request.getParameter("id");
		String fNextReportId = request.getParameter("fNextReportId");
		String fbcph = request.getParameter("fbcph");

		String sql = " select fstate  from t_processreport where  id = ? ";

		String sql2 = " update t_processreport set fstate = '1',FNextReportid = '' where id = ? ";

		String sql5 = " delete from t_process where freportid = ? ";

		ProcessReportEntity p = processReportService.getEntity(ProcessReportEntity.class, id);

		if (p.getNprocess().equals("over")) // 工序在本道工序即结束 单独处理
		{

			String sql3 = " delete from t_process where fbcph = ?  and fprocess = 'over' ";
			String sql4 = " update t_tasks set fstate = '2',frate = NULL where fbcph = ? ";
			systemService.executeSql(sql3, fbcph);
			if(fbcph.contains("-")){
				List<String> list = StringUtil.parseString2ListByCustomerPattern("-", fbcph);
				fbcph = list.get(0);
			}
			systemService.executeSql(sql4, fbcph);
			systemService.executeSql(sql2, id);

			message = "反汇报成功";

		} else
		{

			if (StringUtil.isNotEmpty(fNextReportId))
			{
				ProcessReportEntity p2 = processReportService.getEntity(ProcessReportEntity.class, fNextReportId); // 得到下一工序记录
				
				String fstate = String.valueOf(systemService.findOneForJdbc(sql, fNextReportId).get("fstate")); // 下一工序状态

				if (fstate.equals("2"))
				{
					message = "反汇报失败，该卷号在下道工序已汇报";
					j.setMsg(message);
					return j;

				} else if (fstate.equals("4"))
				{

					message = "反汇报失败，该卷号在下道工序已装炉";
					j.setMsg(message);
					return j;

				} else if (fstate.equals("3"))
				{

					message = "反汇报失败，该卷号在下道工序已分卷";
					j.setMsg(message);
					return j;

				} else
				{
					if (StringUtil.isNotEmpty(p2.getNprocess()) && p2.getFstate().equals("1"))   //  如果下一工序是纵剪或镀铬 则对应的t_cut t_chromate表记录
					{
						if (p2.getNprocess().equals("p10"))  
						{
							String sql6 = " delete from t_cut where fbcph =  " ;
							systemService.executeSql(sql6, fbcph);
							
						} else if (p2.getNprocess().equals("p11"))
						{
							String sql7 = " delete from t_chromate where fbcph =  ? " ;
							systemService.executeSql(sql7, fbcph);
						}

					}
					
					
					
					systemService.deleteEntityById(ProcessReportEntity.class, fNextReportId); // 删除下一工序
					systemService.executeSql(sql5, fNextReportId); // 删除工序
					systemService.executeSql(sql2, id); // 更改本道工序状态

					message = "反汇报成功";

				}

			} else
			{
                
				if(p.getFstate().equals("3"))    //  分卷 反汇报
				{
					String sql6 = " delete from t_processreport where fbcph like ? and create_date > ? ";
					String sql7 = " delete from t_process where fbcph like ? and create_date > ?  ";
					
					systemService.executeSql(sql6, fbcph + '%', p.getCreateDate());
					systemService.executeSql(sql7, fbcph + '%', p.getCreateDate());
					
					p.setFstate("1");
					processReportService.saveOrUpdate(p);
				}
				
				
				
				message = "反汇报失败";

			}

		}

		j.setMsg(message);
		return j;
	}

	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(ProcessReportEntity processReport, HttpServletRequest req)
	{

		if (StringUtil.isNotEmpty(processReport.getId()))
		{
			processReport = processReportService.getEntity(ProcessReportEntity.class, processReport.getId());
			List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
			req.setAttribute("workshopList", workshopList);
			req.setAttribute("processReportPage", processReport);
		}

		String process = processReport.getCprocess();

		if (process.equals("p2_1"))
		{
			String hql = "from RollingEntity where  1 = 1 AND fhbid = ?";
			List<RollingEntity> rollingList = systemService.findHql(hql, processReport.getId());
			req.setAttribute("rollingList", rollingList);
			return new ModelAndView("yongxin/process/processReport_p2_1");

		} else if (process.equals("p2_2"))
		{
			String hql = "from RollingEntity where  1 = 1 AND fhbid = ?";
			List<RollingEntity> rollingList = systemService.findHql(hql, processReport.getId());
			req.setAttribute("rollingList", rollingList);
			return new ModelAndView("yongxin/process/processReport_p2_2");
		} else if (process.equals("p4"))
		{
			return new ModelAndView("yongxin/process/processReport_p4");
		} else if (process.equals("p8"))
		{
			return new ModelAndView("yongxin/process/processReport_p8");
		} else if (process.equals("p6"))
		{
			return new ModelAndView("yongxin/process/processReport_p6");
		} else
		{
			return new ModelAndView("yongxin/process/processReport");
		}

	}

	/*
	 * 获得机组列表
	 */
	@RequestMapping(params = "getMatchinegroupList")
	@ResponseBody
	public AjaxJson getMatchinegroupList(HttpServletRequest request)
	{

		String pid = request.getParameter("pid");
		String process = request.getParameter("process");
		if (process.split("_").length > 0)
		{
			String[] processs = process.split("_");
			process = processs[0];
		}

		String sql = "select * from t_matchinegroup where p_id = ? and process = ?";
		List<Map<String, Object>> maplist = null;
		try
		{
			maplist = systemService.findForJdbc(sql, pid, process);
		} catch (Exception ex)
		{

		} finally
		{

		}
		String select = "<select id='fmatchinegroup' name='fmatchinegroup'>";
		for (Map<String, Object> map : maplist)
		{
			select += "<option value=" + map.get("name") + ">" + map.get("name") + "</option>";
		}

		AjaxJson j = new AjaxJson();
		j.setMsg(select);
		// j.setObj(maplist);
		return j;

	}

	/**
	 * 添加工序汇报
	 * 
	 * @param processReport
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "getProcess")
	@ResponseBody
	public AjaxJson getProcess(ProcessReportEntity processReport, HttpServletRequest request)
	{

		String fbcph = request.getParameter("fbcph");
		String fisleft = request.getParameter("fisleft");
		String pid = request.getParameter("pid");
		String ofbcph = "";
		if (fbcph.indexOf("-") > 0)
		{
			ofbcph = fbcph.substring(0, fbcph.indexOf("-"));
		}
		Object[] object = new Object[3];
		object[0] = ofbcph;
		object[1] = fbcph;
		object[2] = fbcph;

		String sql = " select tp.fbcph,tp.fprocess,tp.create_date,dic.typename " + "   from t_process tp  "
				+ "   left join (select tst.typecode,tst.typename " + "    from t_s_type tst,t_s_typegroup tstg  "
				+ "    where tst.typegroupid=tstg.ID  and tstg.typegroupcode='ccgx') dic " + "     on tp.fprocess=dic.typecode      "
				+ "      where tp.fbcph=? and create_date< ( " + "		select min(create_date) from t_process t1 where t1.fbcph=? "
				+ "      ) " + " union " + "   select tp.fbcph,tp.fprocess,tp.create_date,dic.typename " + "   from t_process tp  "
				+ "   left join (select tst.typecode,tst.typename " + "    from t_s_type tst,t_s_typegroup tstg  "
				+ "    where tst.typegroupid=tstg.ID  and tstg.typegroupcode='ccgx') dic " + "     on tp.fprocess=dic.typecode     "
				+ "  where tp.fbcph=?    order by tp.create_date ";

		String sql2 = "select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql2 += " where tst.typegroupid=tstg.ID ";
		sql2 += " and tstg.typegroupcode='ccgx'";

		List<Map<String, Object>> maplist = null;
		List<Map<String, Object>> maplist2 = null;
		try
		{
			maplist = systemService.findForJdbc(sql, object);
			maplist2 = systemService.findForJdbc(sql2, null);
		} catch (Exception ex)
		{

		} finally
		{

		}
		AjaxJson j = new AjaxJson();
		j.setObj(maplist);
		j.setMsg(createSelecte(maplist2));

		return j;
	}

	private String createSelecte(List<Map<String, Object>> maplist)
	{
		String select = "<select id='nprocess' name='nprocess'><option value=''>请选择</option>";
		for (Map<String, Object> map : maplist)
		{
			select += "<option value=" + map.get("typecode") + ">" + map.get("typename") + "</option>";
		}
		select = select.replaceAll(select.substring(67, 98), "");
		return select;
	}
	
	
	/**
	 * 导出excel 使用模板     已完工
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public void exportXlsByT(ProcessReportEntity processReport,HttpServletRequest request,HttpServletResponse response, DataGrid dataGrid) {
		response.setContentType("application/vnd.ms-excel");
		String codedFileName = null;
		OutputStream fOut = null;
		try {
			codedFileName = "已完工报表";
			// 根据浏览器进行转码，使其支持中文文件名
			if (BrowserUtils.isIE(request)) {
				response.setHeader(
						"content-disposition",
						"attachment;filename="
								+ java.net.URLEncoder.encode(codedFileName,
										"UTF-8") + ".xlsx");//这个地方要修改成和模板一样的文件类型
			} else {
				String newtitle = new String(codedFileName.getBytes("UTF-8"),
						"ISO8859-1");
				response.setHeader("content-disposition",
						"attachment;filename=" + newtitle + ".xlsx");
			}
			
			
			
			Map<String,Object> map = new HashMap<String, Object>();
			
			
			// 产生工作簿对象
			Workbook workbook = null;
			CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
			
			String type = request.getParameter("type");
			//查询条件组装器
			if (type.equals("S"))
			{
				cq.like("fbcph", "S%");
				map.put("steelType", "不锈钢");
				
			} else if (type.equals("Y"))
			{
				cq.like("fbcph", "Y%");
				map.put("steelType", "碳钢");
				
			}else if(type.equals("ALL")){
				map.put("steelType", "碳钢不锈钢");
			}
			
			cq.eq("fstate", "2");
			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
			List<ProcessReportEntity> processReports = this.processReportService.getListByCriteriaQuery(cq,false);
			
			
			workbook = new ExcelExportOfTemplateUtil().createExcleByTemplate(new TemplateExportParams("export/template/exportTemp3.xlsx"),
					ProcessReportEntity.class, processReports,map);
			fOut = response.getOutputStream();
			workbook.write(fOut);
		} catch (Exception e) {
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {
				
			}
		}
	}
   
	
	/**
	 * 导出excel 使用模板     在制品
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT2")
	public void exportXlsByT2(MakingReportEntity processReport,HttpServletRequest request,HttpServletResponse response, DataGrid dataGrid) {
		response.setContentType("application/vnd.ms-excel");
		String codedFileName = null;
		OutputStream fOut = null;
		try {
			codedFileName = "在制品报表";
			// 根据浏览器进行转码，使其支持中文文件名
			if (BrowserUtils.isIE(request)) {
				response.setHeader(
						"content-disposition",
						"attachment;filename="
								+ java.net.URLEncoder.encode(codedFileName,
										"UTF-8") + ".xlsx");//这个地方要修改成和模板一样的文件类型
			} else {
				String newtitle = new String(codedFileName.getBytes("UTF-8"),
						"ISO8859-1");
				response.setHeader("content-disposition",
						"attachment;filename=" + newtitle + ".xlsx");
			}
			
			
			
			Map<String,Object> map = new HashMap<String, Object>();
			
			
			// 产生工作簿对象
			Workbook workbook = null;
			CriteriaQuery cq = new CriteriaQuery(MakingReportEntity.class, dataGrid);
			
			String type = request.getParameter("type");
			//查询条件组装器
			if (type.equals("S"))
			{
				cq.like("fbcph", "S%");
				map.put("steelType", "不锈钢");
				
			} else if (type.equals("Y"))
			{
				cq.like("fbcph", "Y%");
				map.put("steelType", "碳钢");
				
			}else if(type.equals("ALL")){
				map.put("steelType", "碳钢不锈钢");
			}
			
			cq.in("fstate", new Object[] { "0", "1", "4" });
			org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
			List<MakingReportEntity> processReports = this.processReportService.getListByCriteriaQuery(cq,false);
			
			
			workbook = new ExcelExportOfTemplateUtil().createExcleByTemplate(new TemplateExportParams("export/template/exportTemp4.xlsx"),
					MakingReportEntity.class, processReports,map);
			fOut = response.getOutputStream();
			workbook.write(fOut);
		} catch (Exception e) {
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {
				
			}
		}
	}
}
